import { memo, useEffect, useState } from 'react'
import { Flex, Typography } from 'antd'
import style from './cardStyle.module.less'
import classNames from 'classnames'
import { useSearchParams } from 'react-router-dom'
interface CardListDataItem {
  label: string
  value?: string
  tag?: string
  selected?: boolean
}

interface CardListDataType {
  cardListData: CardListDataItem[]
  handleClick: any
}

const { Text } = Typography

const CardList = ({ cardListData, handleClick }: CardListDataType) => {
  const [searchParams] = useSearchParams()
  const [selectedIndex, setSelectedIndex] = useState<any>()

  const handleCardsClick = (item: any, index: any) => {
    if (index !== selectedIndex) {
      setSelectedIndex(index)
      handleClick(item)
    } else {
      setSelectedIndex(null)
      handleClick()
    }
  }
  useEffect(() => {
    setSelectedIndex(null)
    if (searchParams.get('tab')) {
      setTimeout(() => {
        const _index = cardListData.findIndex((item) => item.label === searchParams.get('tab'))
        setSelectedIndex(_index)
        handleClick(cardListData[_index])
      }, 30)
    }
  }, [cardListData])

  return (
    <Flex gap={4} wrap="nowrap" align="flex-start">
      <div className={style.cardBoxWrap}>
        {cardListData.map<React.ReactNode>((card, index) => (
          <div
            key={`${card.label}${card.tag}${index}`}
            className={classNames([
              style.cardBox,
              selectedIndex === index ? style.clicked : '',
              card.tag === '世界级'
                ? style.worldLevel
                : card.tag === '国家级'
                  ? style.countryLevel
                  : card.tag === '省级'
                    ? style.provinceLevel
                    : card.tag === '市级'
                      ? style.cityLevel
                      : ''
            ])}
            onClick={() => handleCardsClick(card, index)}>
            <div className={style.labelBox}>
              {/* <div className={style.label}>{card.label}</div> */}
              <Text style={{ width: 166 }} ellipsis={{ tooltip: card.label }}>
                {card.label}
              </Text>
              <div
                className={classNames([
                  style.tag,
                  card.tag === '世界级'
                    ? style.red
                    : card.tag === '国家级'
                      ? style.purple
                      : card.tag === '省级'
                        ? style.blue
                        : card.tag === '市级'
                          ? style.green
                          : ''
                ])}>
                {card.tag}
              </div>
            </div>
            <div className={style.valueBox}>
              <span className={style.value}>{card.value}</span>
              <span className={style.unit}>家</span>
            </div>
          </div>
        ))}
      </div>
    </Flex>
  )
}

export default memo(CardList)
